package initialize

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"qm_system_server/server/global"
	"strconv"
)

func InitGrpc(flag string) (*grpc.ClientConn, error) {
	addr := getNacosServerIp(flag)
	conn, err := grpc.Dial(addr, grpc.WithInsecure())
	if err != nil {
		global.GVA_LOG.Error("operateAddr client connect failed", zap.Error(err))
	}
	global.GVA_LOG.Info("operateAddr client connect success")
	return conn, err
}

func getNacosServerIp(flag string) string {
	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.GVA_CONFIG.Nacos.NameSpaceId,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		BeatInterval:        5000,
		LogLevel:            "debug",
	}

	// 至少一个ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      global.GVA_CONFIG.Nacos.Addr,
			ContextPath: "/nacos",
			Port:        uint64(global.GVA_CONFIG.Nacos.Port),
			Scheme:      "http",
		},
	}

	// 创建服务发现客户端的另一种方式 (推荐)
	namingClient, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		fmt.Println("clients.NewNamingClient error")
	}

	// SelectOneHealthyInstance将会按加权随机轮询的负载均衡策略返回一个健康的实例
	// 实例必须满足的条件：health=true,enable=true and weight>0
	instance, err := namingClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
		ServiceName: flag,
		GroupName:   "DEFAULT_GROUP",     // 默认值DEFAULT_GROUP
		Clusters:    []string{"DEFAULT"}, // 默认值DEFAULT
	})

	addr := instance.Ip + ":" + strconv.Itoa(int(instance.Port))
	return addr
}
